{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# How to generate multiple queries to retrieve data for\n",
        "\n",
        ":::info Prerequisites\n",
        "\n",
        "This guide assumes familiarity with the following concepts:\n",
        "\n",
        "- [Vector stores](/docs/concepts/#vectorstores)\n",
        "- [Retrievers](/docs/concepts/retrievers)\n",
        "- [Retrieval-augmented generation (RAG)](/docs/tutorials/rag)\n",
        "\n",
        ":::\n",
        "\n",
        "Distance-based vector database retrieval embeds (represents) queries in high-dimensional space and finds similar embedded documents based on \"distance\".\n",
        "But retrieval may produce different results with subtle changes in query wording or if the embeddings do not capture the semantics of the data well.\n",
        "Prompt engineering / tuning is sometimes done to manually address these problems, but can be tedious.\n",
        "\n",
        "The [`MultiQueryRetriever`](https://api.js.langchain.com/classes/langchain.retrievers_multi_query.MultiQueryRetriever.html) automates the process of prompt tuning by using an LLM to generate multiple queries from different perspectives for a given user input query.\n",
        "For each query, it retrieves a set of relevant documents and takes the unique union across all queries to get a larger set of potentially relevant documents.\n",
        "By generating multiple perspectives on the same question, the `MultiQueryRetriever` can help overcome some of the limitations of the distance-based retrieval and get a richer set of results.\n",
        "\n",
        "## Get started\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/anthropic @langchain/cohere\n",
        "</Npm2Yarn>\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: \"mitochondria is made of lipids\",\n",
            "    metadata: {}\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"mitochondria is the powerhouse of the cell\",\n",
            "    metadata: {}\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Buildings are made out of brick\",\n",
            "    metadata: { id: 1 }\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Buildings are made out of wood\",\n",
            "    metadata: { id: 2 }\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "import { MemoryVectorStore } from \"langchain/vectorstores/memory\";\n",
        "import { CohereEmbeddings } from \"@langchain/cohere\";\n",
        "import { MultiQueryRetriever } from \"langchain/retrievers/multi_query\";\n",
        "import { ChatAnthropic } from \"@langchain/anthropic\";\n",
        "\n",
        "const embeddings = new CohereEmbeddings();\n",
        "\n",
        "const vectorstore = await MemoryVectorStore.fromTexts(\n",
        "  [\n",
        "    \"Buildings are made out of brick\",\n",
        "    \"Buildings are made out of wood\",\n",
        "    \"Buildings are made out of stone\",\n",
        "    \"Cars are made out of metal\",\n",
        "    \"Cars are made out of plastic\",\n",
        "    \"mitochondria is the powerhouse of the cell\",\n",
        "    \"mitochondria is made of lipids\",\n",
        "  ],\n",
        "  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],\n",
        "  embeddings\n",
        ");\n",
        "\n",
        "const model = new ChatAnthropic({\n",
        "  model: \"claude-3-sonnet-20240229\"\n",
        "});\n",
        "\n",
        "const retriever = MultiQueryRetriever.fromLLM({\n",
        "  llm: model,\n",
        "  retriever: vectorstore.asRetriever(),\n",
        "});\n",
        "\n",
        "const query = \"What are mitochondria made of?\";\n",
        "const retrievedDocs = await retriever.invoke(query);\n",
        "\n",
        "/*\n",
        "  Generated queries: What are the components of mitochondria?,What substances comprise the mitochondria organelle?  ,What is the molecular composition of mitochondria?\n",
        "*/\n",
        "\n",
        "console.log(retrievedDocs);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Customization\n",
        "\n",
        "You can also supply a custom prompt to tune what types of questions are generated.\n",
        "You can also pass a custom output parser to parse and split the results of the LLM call into a list of queries."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  Document {\n",
            "    pageContent: \"Mitochondrien bestehen aus Lipiden\",\n",
            "    metadata: {}\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Mitochondrien sind die Energiekraftwerke der Zelle\",\n",
            "    metadata: {}\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Gebäude werden aus Stein hergestellt\",\n",
            "    metadata: { id: 3 }\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Autos werden aus Metall hergestellt\",\n",
            "    metadata: { id: 4 }\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Gebäude werden aus Holz hergestellt\",\n",
            "    metadata: { id: 2 }\n",
            "  },\n",
            "  Document {\n",
            "    pageContent: \"Gebäude werden aus Ziegelsteinen hergestellt\",\n",
            "    metadata: { id: 1 }\n",
            "  }\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "import { LLMChain } from \"langchain/chains\";\n",
        "import { pull } from \"langchain/hub\";\n",
        "import { BaseOutputParser } from \"@langchain/core/output_parsers\";\n",
        "import { PromptTemplate } from \"@langchain/core/prompts\";\n",
        "\n",
        "\n",
        "type LineList = {\n",
        "  lines: string[];\n",
        "};\n",
        "\n",
        "class LineListOutputParser extends BaseOutputParser<LineList> {\n",
        "  static lc_name() {\n",
        "    return \"LineListOutputParser\";\n",
        "  }\n",
        "\n",
        "  lc_namespace = [\"langchain\", \"retrievers\", \"multiquery\"];\n",
        "\n",
        "  async parse(text: string): Promise<LineList> {\n",
        "    const startKeyIndex = text.indexOf(\"<questions>\");\n",
        "    const endKeyIndex = text.indexOf(\"</questions>\");\n",
        "    const questionsStartIndex =\n",
        "      startKeyIndex === -1 ? 0 : startKeyIndex + \"<questions>\".length;\n",
        "    const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex;\n",
        "    const lines = text\n",
        "      .slice(questionsStartIndex, questionsEndIndex)\n",
        "      .trim()\n",
        "      .split(\"\\n\")\n",
        "      .filter((line) => line.trim() !== \"\");\n",
        "    return { lines };\n",
        "  }\n",
        "\n",
        "  getFormatInstructions(): string {\n",
        "    throw new Error(\"Not implemented.\");\n",
        "  }\n",
        "}\n",
        "\n",
        "// Default prompt is available at: https://smith.langchain.com/hub/jacob/multi-vector-retriever-german\n",
        "const prompt: PromptTemplate = await pull(\n",
        "  \"jacob/multi-vector-retriever-german\"\n",
        ");\n",
        "\n",
        "const vectorstore = await MemoryVectorStore.fromTexts(\n",
        "  [\n",
        "    \"Gebäude werden aus Ziegelsteinen hergestellt\",\n",
        "    \"Gebäude werden aus Holz hergestellt\",\n",
        "    \"Gebäude werden aus Stein hergestellt\",\n",
        "    \"Autos werden aus Metall hergestellt\",\n",
        "    \"Autos werden aus Kunststoff hergestellt\",\n",
        "    \"Mitochondrien sind die Energiekraftwerke der Zelle\",\n",
        "    \"Mitochondrien bestehen aus Lipiden\",\n",
        "  ],\n",
        "  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],\n",
        "  embeddings\n",
        ");\n",
        "const model = new ChatAnthropic({});\n",
        "const llmChain = new LLMChain({\n",
        "  llm: model,\n",
        "  prompt,\n",
        "  outputParser: new LineListOutputParser(),\n",
        "});\n",
        "const retriever = new MultiQueryRetriever({\n",
        "  retriever: vectorstore.asRetriever(),\n",
        "  llmChain,\n",
        "});\n",
        "\n",
        "const query = \"What are mitochondria made of?\";\n",
        "const retrievedDocs = await retriever.invoke(query);\n",
        "\n",
        "/*\n",
        "  Generated queries: Was besteht ein Mitochondrium?,Aus welchen Komponenten setzt sich ein Mitochondrium zusammen?  ,Welche Moleküle finden sich in einem Mitochondrium?\n",
        "*/\n",
        "\n",
        "console.log(retrievedDocs);"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Next steps\n",
        "\n",
        "You've now learned how to use the `MultiQueryRetriever` to query a vector store with automatically generated queries.\n",
        "\n",
        "See the individual sections for deeper dives on specific retrievers, the [broader tutorial on RAG](/docs/tutorials/rag), or this section to learn how to\n",
        "[create your own custom retriever over any data source](/docs/how_to/custom_retriever/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Deno",
      "language": "typescript",
      "name": "deno"
    },
    "language_info": {
      "file_extension": ".ts",
      "mimetype": "text/x.typescript",
      "name": "typescript",
      "nb_converter": "script",
      "pygments_lexer": "typescript",
      "version": "5.3.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}